const Router = require('koa-router')
const Fav = require('../model/fav.js')
// const Goods = require('../model/goods.js')
const jwt = require('jsonwebtoken')
const fav = new Router()

// 查询收藏列表
fav.get('/find', async ctx => {
    try {
        // 请求头中的token 解析后带有‘Bearer ’和空格，因此需要按空格截取
        let getToken = ctx.request.header.authorization.split(' ')[1]
        // 将截取后的字符串再通过decode反解出openid
        let openid = jwt.decode(getToken).info
        let pageIndex = ctx.query.pageIndex || 1 // 当前页
        let pageSize = parseInt(ctx.query.pageSize || 10) // 每页数量
        let pageSkip = (pageIndex - 1) * pageSize

        /* let res = await Fav.find({ userOpenid: openid, favStatus: true }).sort({ createTime: -1 }).skip(pageSkip).limit(pageSize)
        let goodsRes = await Goods.find()
        let favRes = goodsRes.filter(item => res.some(v => item._id == v.goodsId && v.favStatus === true)) */
        let favRes = await Fav.aggregate([
            {
                $lookup: {
                    from: "goods",
                    localField: "goodsId",
                    foreignField: "_id",
                    as: "goodsDetail"
                }
            },
            {
                $match: { userOpenid: openid, favStatus: true }
            }
        ]).sort({ createTime: -1 }).skip(pageSkip).limit(pageSize)

        if (favRes) {
            ctx.body = {
                code: 2,
                data: favRes
            }
        } else {
            ctx.body = {
                code: 2,
                data: [],
                msg: '暂无数据'
            }
        }

    } catch (error) {
        //TODO handle the exception
        console.log(error)
    }
})
// 添加/取消收藏列表
fav.get('/fav', async ctx => {
    try {
        let getToken = ctx.request.header.authorization.split(' ')[1]
        let openid = jwt.decode(getToken).info
        let gid = ctx.query.id // 商品类型

        let res = await Fav.findOne({ userOpenid: openid, goodsId: gid })
        if (!res) {
            let data = new Fav({
                userOpenid: openid,
                goodsId: gid,
                favStatus: true
            })
            await data.save()
            ctx.body = {
                code: 2,
                msg: "收藏成功"
            }
        } else {
            let isFav = res.favStatus
            await Fav.deleteOne({ goodsId: gid })
            ctx.body = {
                code: 2,
                msg: isFav ? '取消收藏' : '收藏成功'
            }
        }

    } catch (error) {
        //TODO handle the exception
        console.log(error)
    }
})

// 获取收藏状态
fav.get('/favStatus', async ctx => {
    try {
        let getToken = ctx.request.header.authorization.split(' ')[1]
        let openid = jwt.decode(getToken).info
        let gid = ctx.query.id // 商品类型

        let res = await Fav.find({ userOpenid: openid, goodsId: gid })
        if (res) {
            ctx.body = {
                code: 2,
                isFav: res[0]?.favStatus || false
            }
        } else {
            ctx.body = {
                code: 2,
                isFav: false
            }
        }

    } catch (error) {
        //TODO handle the exception
        console.log(error)
    }
})

fav.get('/delfav', async ctx => {
    try {
        let getToken = ctx.request.header.authorization.split(' ')[1]
        let openid = jwt.decode(getToken).info
        let gid = ctx.query.id // 商品类型

        let res = await Fav.findOne({ userOpenid: openid, goodsId: gid })

        if (res) {
            await Fav.deleteOne({ goodsId: gid })
            ctx.body = {
                code: 2,
                msg: "删除成功"
            }
        } else {
            ctx.body = {
                code: 0,
                msg: "删除失败"
            }
        }



    } catch (error) {
        console.log(error);
    }
})

module.exports = fav